package com.comtime.manager;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class ShakeManager implements SensorEventListener {
	private Context mContext;
	private static final int SPEED_SHRESHOLD = 3000;
	private static final int UPTATE_INTERVAL_TIME = 70;
	private SensorManager sensorManager;
	private Sensor sensor;
	private OnShakeListener onShakeListener;

	
	private float lastX;
	private float lastY;
	private float lastZ;
	 
	private long lastUpdateTime;
	
	public ShakeManager(Context context, OnShakeListener onShakeListener) {
		super();
		mContext = context;
		this.onShakeListener = onShakeListener;
	}

	public void startUpdateListener() {
		sensorManager = (SensorManager) mContext
				.getSystemService(Context.SENSOR_SERVICE);
		if (sensorManager != null) {
			sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		}
		if (sensor != null) {
			sensorManager.registerListener(this, sensor,
					SensorManager.SENSOR_DELAY_GAME);
		}
	}

	public void stopUpdateListener() {
		if (sensorManager != null)
			sensorManager.unregisterListener(this);
	}

	// 摇晃监听接口
	public interface OnShakeListener {
		public void onShaked();
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		long currentUpdateTime = System.currentTimeMillis();
		long timeInterval = currentUpdateTime - lastUpdateTime;
		if (timeInterval < UPTATE_INTERVAL_TIME)
			return;
		lastUpdateTime = currentUpdateTime;
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];
		float deltaX = x - lastX;
		float deltaY = y - lastY;
		float deltaZ = z - lastZ;
		lastX = x;
		lastY = y;
		lastZ = z;
		double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ
				* deltaZ)
				/ timeInterval * 10000;
		Log.e("", "speed:"+speed);
		// 达到速度阀值，发出提示
		if (speed >= SPEED_SHRESHOLD) {
			onShakeListener.onShaked();
		}
	}
}
